import Message from 'tdesign-miniprogram/message/index';
import request from '~/api/request';

// 获取应用实例
// const app = getApp()

Page({
  data: {
    enable: false,
    searchPlaceholder: '荣耀运动手环',
    swiperList: [],
    cardInfo: [],
    // 分类图标数据
    categoryIcons: [
      { id: 1, name: '品牌专区', icon: '/static/home/品牌词.png' },
      { id: 2, name: '限时折扣', icon: '/static/home/限时.png' },
      { id: 3, name: '每日签到', icon: '/static/home/签到.png' },
      { id: 4, name: '天天领券', icon: '/static/home/优惠券.png' },
      { id: 5, name: '免费领好礼', icon: '/static/home/礼品.png' },
    ],
    category: [],
    // 商品列表数据
    productList: [
      // { 
      //   id: 1, 
      //   title: '【定制球鞋】Anta安踏O', 
      //   price: '309', 
      //   sold: '662人付款', 
      //   image: '/assets/products/shoes.jpg' 
      // },
      // { 
      //   id: 2, 
      //   title: 'Supreme Box Logo Tee', 
      //   price: '899', 
      //   sold: '1253人付款', 
      //   image: '/assets/products/supreme.jpg' 
      // },
      // { 
      //   id: 3, 
      //   title: 'Nike Air Force 1 Low', 
      //   price: '799', 
      //   sold: '4367人付款', 
      //   image: '/assets/products/nike.jpg' 
      // },
      // { 
      //   id: 4, 
      //   title: 'Adidas Yeezy Boost 350', 
      //   price: '1299', 
      //   sold: '2134人付款', 
      //   image: '/assets/products/adidas.jpg' 
      // }
    ],
    // 用户信息
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
  },
  // 生命周期
  async onReady() {
    try {
      const [cardRes, swiperRes] = await Promise.all([
        request('/home/cards').then((res) => res.data),
        request('/home/swipers').then((res) => res.data),
      ]);

      // 如果接口返回成功，更新数据
      if (cardRes && swiperRes) {
        this.setData({
          cardInfo: cardRes.data,
          focusCardInfo: cardRes.data.slice(0, 3),
          swiperList: swiperRes.data,
        });
      }
    } catch (error) {
      console.error('加载数据失败', error);
      // 可以添加错误提示
      Message.error({
        context: this,
        offset: [120, 32],
        duration: 3000,
        content: '数据加载失败，请稍后重试',
      });
    }
  },
  
  onLoad(option) {
    this.fetchItemData();
    this.fetchCategoryData();
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }
    if (option.oper) {
      let content = '';
      if (option.oper === 'release') {
        content = '发布成功';
      } else if (option.oper === 'save') {
        content = '保存成功';
      }
      this.showOperMsg(content);
    }
  },
  
  onRefresh() {
    this.refresh();
  },
  
  async refresh() {
    this.setData({
      enable: true,
    });
    
    try {
      const [cardRes, swiperRes] = await Promise.all([
        request('/home/cards').then((res) => res.data),
        request('/home/swipers').then((res) => res.data),
      ]);

      setTimeout(() => {
        this.setData({
          enable: false,
          cardInfo: cardRes.data,
          swiperList: swiperRes.data,
        });
        
        // 添加刷新成功提示
        Message.success({
          context: this,
          offset: [120, 32],
          duration: 2000,
          content: '刷新成功',
        });
      }, 1000);
    } catch (error) {
      this.setData({
        enable: false,
      });
      
      Message.error({
        context: this,
        offset: [120, 32],
        duration: 3000,
        content: '刷新失败，请稍后重试',
      });
    }
  },
  
  showOperMsg(content) {
    Message.success({
      context: this,
      offset: [120, 32],
      duration: 3000,
      content,
    });
  },
  
  goProductDetail(e) {
    const productId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/product/detail/index?id=${productId}`,
    });
  },
  fetchItemData() {
    wx.request({
      url: 'http://localhost:8080/get/item', // 替换为你的接口地址
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          const jsonData = res.data;
          // console.log(jsonData)
          this.setData({
            productList: jsonData,
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none',
        });
      },
    });
  },

  fetchCategoryData() {
    wx.request({
      url: 'http://localhost:8080/get/category', // 替换为你的接口地址
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          const jsonData = res.data;
          // console.log(jsonData)
          this.setData({
            category: jsonData,
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none',
        });
      },
    });
  },

  // 跳转到分类页面
  goToCategory(e) {
    const categoryId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/category/index?id=${categoryId}`,
    });
  },
  
  // 跳转到购物车
  goToCart() {
    wx.navigateTo({
      url: '/pages/cart/index',
    });
  },
  
  // 跳转到用户中心
  goToUser() {
    wx.navigateTo({
      url: '/pages/user/index',
    });
  },
});